<template>
  <div class="color-flow-test">
    <h2>🎨 颜色分配流程测试</h2>
    
    <div class="test-section">
      <h3>1. 连接测试</h3>
      <el-button @click="connect" :disabled="isConnected" type="primary">
        连接服务器
      </el-button>
      <el-button @click="disconnect" :disabled="!isConnected" type="danger">
        断开连接
      </el-button>
      <p>连接状态: {{ isConnected ? '✅ 已连接' : '❌ 未连接' }}</p>
    </div>
    
    <div class="test-section">
      <h3>2. 房间测试</h3>
      <el-button @click="createRoom" :disabled="!isConnected" type="success">
        创建房间
      </el-button>
      <el-button @click="joinRoom" :disabled="!isConnected" type="warning">
        加入房间
      </el-button>
      <el-button @click="leaveRoom" :disabled="!isConnected" type="info">
        离开房间
      </el-button>
      <p>房间ID: {{ roomId || '无' }}</p>
    </div>
    
    <div class="test-section">
      <h3>3. 当前玩家状态</h3>
      <div class="player-info">
        <p><strong>ID:</strong> {{ currentPlayer?.id || '无' }}</p>
        <p><strong>昵称:</strong> {{ currentPlayer?.nickname || '无' }}</p>
        <p><strong>头像颜色:</strong> 
          <span class="color-display" :style="{ backgroundColor: currentPlayer?.avatarColor }">
            {{ currentPlayer?.avatarColor || '无' }}
          </span>
        </p>
        <p><strong>画笔颜色:</strong> 
          <span class="color-display" :style="{ backgroundColor: currentPlayer?.brushColor }">
            {{ currentPlayer?.brushColor || '无' }}
          </span>
        </p>
        <p><strong>是否房主:</strong> {{ currentPlayer?.isOwner ? '是' : '否' }}</p>
      </div>
    </div>
    
    <div class="test-section">
      <h3>4. 玩家列表</h3>
      <div v-for="player in players" :key="player.id" class="player-item">
        <span class="player-name">{{ player.nickname }}</span>
        <span class="color-display" :style="{ backgroundColor: player.avatarColor }">
          {{ player.avatarColor }}
        </span>
        <span class="color-display" :style="{ backgroundColor: player.brushColor }">
          {{ player.brushColor }}
        </span>
        <span v-if="player.isOwner" class="owner-badge">👑</span>
      </div>
    </div>
    
    <div class="test-section">
      <h3>5. 调试工具</h3>
      <el-button @click="runTest" type="primary">运行测试脚本</el-button>
      <el-button @click="checkStore" type="warning">检查Store状态</el-button>
      <el-button @click="clearLogs" type="info">清空日志</el-button>
      <el-button @click="exportLogs" type="success">导出日志</el-button>
    </div>
    
    <div class="test-section">
      <h3>6. 实时日志</h3>
      <div class="log-container">
        <div v-for="log in logs.slice(-20)" :key="log.id" class="log-item">
          <span class="log-time">{{ log.timestamp }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { createSignalRService } from '@/services/socketService'
import { useGameStore } from '@/stores/game'
import { colorDebugger } from '@/utils/colorDebugger'

const gameStore = useGameStore()
const isConnected = ref(false)
const roomId = ref('')
const currentPlayer = ref(null)
const players = ref([])
const logs = ref([])

const signalRService = createSignalRService(gameStore)

function addLog(message, data = null) {
  const timestamp = new Date().toLocaleTimeString()
  const logEntry = {
    timestamp,
    message,
    data,
    id: Date.now() + Math.random()
  }
  logs.value.push(logEntry)
  if (logs.value.length > 100) logs.value.shift()
  
  // 同时添加到颜色调试器
  if (data) {
    colorDebugger.addLog(message, data)
  } else {
    colorDebugger.addLog(message)
  }
}

async function connect() {
  try {
    addLog('正在连接...')
    await signalRService.connect()
    isConnected.value = true
    addLog('✅ 连接成功')
  } catch (error) {
    addLog(`❌ 连接失败: ${error.message}`)
  }
}

async function disconnect() {
  try {
    await signalRService.disconnect()
    isConnected.value = false
    addLog('🔌 已断开连接')
  } catch (error) {
    addLog(`❌ 断开失败: ${error.message}`)
  }
}

async function createRoom() {
  try {
    const roomCode = 'test-' + Math.random().toString(36).substr(2, 6)
    const playerId = 'player-' + Math.random().toString(36).substr(2, 9)
    
    addLog(`🏠 创建房间: ${roomCode}`)
    await signalRService.createRoom(roomCode, '测试房间', 6, '', playerId, '测试房主')
    roomId.value = roomCode
    addLog(`✅ 房间创建成功: ${roomCode}`)
  } catch (error) {
    addLog(`❌ 创建房间失败: ${error.message}`)
  }
}

async function joinRoom() {
  try {
    const playerId = 'player-' + Math.random().toString(36).substr(2, 9)
    const targetRoom = roomId.value || 'test-room'
    
    addLog(`👤 加入房间: ${targetRoom}`)
    await signalRService.joinRoom(targetRoom, playerId, '测试玩家')
    addLog(`✅ 成功加入房间: ${targetRoom}`)
  } catch (error) {
    addLog(`❌ 加入房间失败: ${error.message}`)
  }
}

async function leaveRoom() {
  try {
    if (currentPlayer.value && roomId.value) {
      addLog('👋 离开房间...')
      await signalRService.leaveRoom(roomId.value, currentPlayer.value.id)
      addLog('✅ 已离开房间')
      currentPlayer.value = null
      roomId.value = ''
    }
  } catch (error) {
    addLog(`❌ 离开房间失败: ${error.message}`)
  }
}

function runTest() {
  addLog('🧪 运行测试脚本...')
  
  // 检查全局对象
  addLog(`检查全局对象: colorDebugger=${!!window.colorDebugger}, gameStore=${!!window.gameStore}`)
  
  // 检查 GameStore 状态
  addLog('📊 GameStore 状态检查', {
    currentPlayer: gameStore.currentPlayer,
    players: gameStore.players,
    currentRoom: gameStore.currentRoom,
    isConnected: gameStore.isConnected
  })
  
  // 检查颜色一致性
  if (window.colorDebugger) {
    const issues = window.colorDebugger.checkColorConsistency(gameStore.players)
    if (issues.length === 0) {
      addLog('✅ 颜色一致性检查通过')
    } else {
      addLog(`⚠️ 发现 ${issues.length} 个颜色问题`, issues)
    }
  }
}

function checkStore() {
  addLog('🔍 检查Store状态...')
  addLog('当前玩家', gameStore.currentPlayer)
  addLog('玩家列表', gameStore.players)
  addLog('房间信息', gameStore.currentRoom)
}

function clearLogs() {
  logs.value = []
  colorDebugger.clearLogs()
  addLog('🧹 日志已清空')
}

function exportLogs() {
  colorDebugger.exportLogs()
  addLog('📤 日志已导出')
}

onMounted(() => {
  addLog('🚀 页面已加载')
  
  // 监听游戏状态变化
  const unsubscribe = gameStore.$subscribe((mutation, state) => {
    if (mutation.type === 'patch') {
      players.value = state.players
      if (state.currentPlayer) {
        currentPlayer.value = state.currentPlayer
        addLog(`🎨 当前玩家颜色更新: 头像=${state.currentPlayer.avatarColor}, 画笔=${state.currentPlayer.brushColor}`)
      }
    }
  })
  
  // 监听SignalR事件
  signalRService.on('Connected', () => {
    addLog('🔗 SignalR连接成功')
  })
  
  signalRService.on('PlayerJoined', (data) => {
    addLog(`👤 玩家加入: ${data.Nickname}`, {
      avatarColor: data.AvatarColor,
      brushColor: data.BrushColor
    })
  })
  
  signalRService.on('RoomCreated', (data) => {
    addLog(`🏠 房间创建成功: ${data.RoomCode}`, {
      avatarColor: data.AvatarColor,
      brushColor: data.BrushColor
    })
  })
  
  signalRService.on('RoomInfo', (data) => {
    addLog(`📋 房间信息更新: ${data.Players?.length || 0} 个玩家`)
  })
  
  // 清理函数
  onUnmounted(() => {
    unsubscribe()
    signalRService.off('Connected')
    signalRService.off('PlayerJoined')
    signalRService.off('RoomCreated')
    signalRService.off('RoomInfo')
  })
})
</script>

<style scoped>
.color-flow-test {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.test-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.test-section h3 {
  margin-top: 0;
  color: #333;
}

.player-info p {
  margin: 8px 0;
}

.player-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  border: 1px solid #ddd;
  margin-bottom: 5px;
  border-radius: 4px;
  background: white;
}

.player-name {
  font-weight: bold;
  min-width: 100px;
}

.color-display {
  display: inline-block;
  width: 80px;
  height: 24px;
  border-radius: 4px;
  color: white;
  text-align: center;
  font-size: 12px;
  line-height: 24px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  font-family: monospace;
}

.owner-badge {
  font-size: 16px;
}

.log-container {
  background: #2d3748;
  color: #e2e8f0;
  padding: 15px;
  border-radius: 8px;
  max-height: 300px;
  overflow-y: auto;
  font-family: monospace;
  font-size: 12px;
}

.log-item {
  margin-bottom: 5px;
  padding: 2px 0;
}

.log-time {
  color: #68d391;
  margin-right: 10px;
}

.log-message {
  color: #e2e8f0;
}
</style>
